//*********************************************************************
//		Copyright (c) 2003 - 2008 Microsoft Corporation.
//      This code is provided under Microsoft Public License, which can be found at
//      http://www.microsoft.com/resources/sharedsource/licensingbasics/publiclicense.mspx 
//
// @File: Service.cs
//
// Purpose: Service controls
//
//
//
// Notes: 
//
//
//	
// History: 
//     @Version: V2.1
//
//     10/31/08 PGV 2.1.001.0 Starting V2.1 (based on 2.0.002.0 code)
//
//
// @EndHeader@
//*********************************************************************


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

namespace PerfService
{
	public class SQLH2PerfCollector: System.ServiceProcess.ServiceBase
	{
		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

        static Guid iGuid;
        public static Guid InstallationGuid { get { return iGuid; } }
		public static readonly Guid RunGuid = Guid.NewGuid ();
		static string ServiceDir;
		PerfMgr pf;
		static EventLog eLog;
		int Status = 0;

		public static void Log (string message, EventLogEntryType type, int eventId)
		{
			if (eventId == 99 && !Constants.VerboseLogging) return;
			eLog.WriteEntry (message, type, eventId);
		}

		public static void EmergencyExit ()
		{
			Log ("SQLH2PerfCollector is unable to continue. Service terminates.", EventLogEntryType.Error, 4);
			Environment.Exit (1);
		}

		public SQLH2PerfCollector()
		{
			// This call is required by the Windows.Forms Component Designer.
			InitializeComponent();

			this.CanPauseAndContinue = false;
			this.AutoLog = true;
			this.CanStop = true;
			this.CanShutdown = true;

			try
			{
				ServiceDir = Path.GetDirectoryName(Application.ExecutablePath);
				Constants.OutputDir = ServiceDir+"\\Data";

                RegistryKey rk = (Registry.LocalMachine).OpenSubKey("SOFTWARE");
                rk = rk.OpenSubKey("Microsoft");
                rk = rk.OpenSubKey("SQLH2PerfCollector");
                if (rk == null)
                {
                    throw new Exception ("Can't find Registry key required to start the service");
                }
				string s_GUID = (string)rk.GetValue ("iGUID");
				iGuid = new Guid (s_GUID);
				Constants.OutputDir = (string)rk.GetValue ("OutputDir");

                // Generate exception if path is incorrect 
				if (!Directory.Exists (Constants.OutputDir))
				{
					throw new Exception ("Output directory "+Constants.OutputDir+" doesn't exist");
				}

				// Comment the next string for Release build
				//Debug.Listeners.Add (new TextWriterTraceListener (new FileStream (Constants.OutputDir+"\\debuglog.txt", FileMode.Create, FileAccess.Write)));

				Log ("Starting SQLH2PerfCollector ver."+Constants.Version+Environment.NewLine
					+" iGUID="+InstallationGuid+Environment.NewLine
					+" rGUID="+RunGuid, EventLogEntryType.Information, 1);
				Log ("Framework Version = "+Environment.Version, EventLogEntryType.Information, 99);

				string iniFileName = SQLH2PerfCollector.ServiceDir+"\\"+Constants.ConfigFileName;
				if (!File.Exists (iniFileName))
				{
					throw (new Exception ("Can't find initialization file "+Constants.ConfigFileName));
				}

				pf = new PerfMgr (iniFileName);
				pf.Init ();
			}
			catch (Exception ex)
			{
				Log (ex.Message, EventLogEntryType.Error, 60);
    			Log ("Service initialization failed", EventLogEntryType.Error, 3);
				Status = 0;
				Environment.Exit (1);
				return;
			}

			Status = 1;
		}

		// The main entry point for the process
		static void Main()
		{
            SQLH2PerfCollector collector = new SQLH2PerfCollector ();
			System.ServiceProcess.ServiceBase.Run (collector);
            collector.Dispose ();
		}

		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			eLog = new System.Diagnostics.EventLog();
			((System.ComponentModel.ISupportInitialize)(eLog)).BeginInit();
			// 
			// eLog
			// 
			eLog.Log = "Application";
			eLog.Source = "SQLH2PerfCollector";
			// 
			// SQLH2PerfCollector
			// 
			this.ServiceName = "SQLH2PerfCollector";
			((System.ComponentModel.ISupportInitialize)(eLog)).EndInit();

		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
            try
            {
                if (disposing)
                {
                    if (components != null)
                    {
                        components.Dispose ();
                    }
                }
            }
            finally
            {
                base.Dispose (disposing);
            }
		}

		/// <summary>
		/// Set things in motion so your service can do its work.
		/// </summary>
		protected override void OnStart(string[] args)
		{
			if (Status == 1) 
			{
				try
				{
					pf.Start ();
				}
				catch (Exception ex)
				{
					SQLH2PerfCollector.Log (ex.Message+" "+ex.StackTrace, EventLogEntryType.Error, 61); 
				}
			}
		}
 
		/// <summary>
		/// Stop this service.
		/// </summary>
		protected override void OnStop()
		{
			if (Status == 1) pf.Stop ();
		}

		protected override void OnShutdown ()
		{
			if (Status == 1) pf.Shutdown ();
		}
	}

	public sealed class Constants
	{
        static readonly Version ver = new Version (((System.Reflection.AssemblyFileVersionAttribute)
            (System.Reflection.Assembly.GetExecutingAssembly ().GetCustomAttributes (
            typeof (System.Reflection.AssemblyFileVersionAttribute), false)[0])).Version);
        static readonly DateTime filestamp = File.GetLastWriteTime (System.Reflection.Assembly.GetExecutingAssembly ().ManifestModule.FullyQualifiedName);
        public static readonly string Version = ver + " " + filestamp.ToString ();
        
		public const string ConfigFileName = "H2PerfConfigFile.xml";
		public const int MaxRetryInterval = 14400;		// 4 hours
		public const int MinRetryInterval = 30;
		public const int MinCollectionInterval = 10;		
		public const int MaxCollectionInterval = 3600;   // 1 hour 
		public const int MinRecorderSleepTime = 3;		// 3 sec
		public const int MaxRecorderSleepTime = 60;		// 1 min
		public const int MinFileSize = 524288;			// 512KB
		public const int AbsoluteMaxFileSize = 10485760;			// 10MB

		public const int MaxCountersPerTarget = 250;		// Security concern
		public const int MaxNumberOfTargets = 250;

		public static int CollectionIntervalSeconds = 120;
		public static int RetryIntervalSeconds = 300;
		public static int RecorderSleepTimeSeconds = 15;
		public static int FileNameResolutionAttempts = 100;   // not exposed
		public static int MaxFileSize = 1048576;
		public static int FileLengthCheckFrequency = 1000;    // not exposed
		public static string OutputDir;
		public static bool UseInvariantCulture = false;
		public static bool VerboseLogging = false;
	}

}
